package com.eims.sls_app.ui.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.LotteryContent;
import com.eims.sls_app.dataaccess.Schemes;
import com.eims.sls_app.dataaccess.CircleBean.CommentBean;
import com.eims.sls_app.dataaccess.CircleBean.SchemeinfoBean;
import com.eims.sls_app.dataaccess.CircleBean.TopicBean;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.CirclePersonInfo;
import com.eims.sls_app.ui.DocumentaryActivity;
import com.eims.sls_app.ui.MyCommonLotteryInfo_jc_other;
import com.eims.sls_app.ui.MyCommonLotteryInfo_other;
import com.eims.sls_app.ui.adapter.CircleAdapter.MyAsynTask;
import com.eims.sls_app.ui.adapter.CircleAdapter.MyHandler;
import com.eims.sls_app.ui.adapter.CircleAdapterMy.GuanzhuAsynTask;
import com.eims.sls_app.ui.adapter.CircleAdapterMy.guanHuMyHandler;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.view.MyToast;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;

public class CirclePersoninfoAdapter extends BaseAdapter {
	private Context context;
	private static final String TAG = "CircleAdapter";
	private List<TopicBean> topicBeans;
	private List<SchemeinfoBean> schemeinfoBeans;
	private List<List<CommentBean>> commentBeanLists;
	private String opt, auth, time, info, imei, crc; // 格式化后的参数
	private MyHandler mHandler;
	private MyAsynTask mMyAsynTask;
	private GuanzhuAsynTask guanzhuAsynTask;
	private guanHuMyHandler gzmHandler;
	private int selectLoctonParse;
	private ProgressDialog pd;
	Schemes scheme;
	private getMyHandler getMyHandler;
	private String getauth, getinfo, gettime, getimei, getcrc, getkey; // 格式化后的参数
	private String getopt = "46"; // 格式化后的 opt
	private String id, sumid, isopen;
	private boolean isJoin = true;

	private String Stoptime;
	private java.text.DecimalFormat df;
	public CirclePersoninfoAdapter(Context context, List<TopicBean> topicBeans, List<SchemeinfoBean> schemeinfoBeans,
			List<List<CommentBean>> commentBeanLists) {
		super();
		this.context = context;
		this.topicBeans = topicBeans;
		this.schemeinfoBeans = schemeinfoBeans;
		this.commentBeanLists = commentBeanLists;

        Log.e(TAG, "CirclePersoninfoAdapter: "+topicBeans.toString() );
		getMyHandler = new getMyHandler();
		df = new java.text.DecimalFormat("#.0");
		// setDate(topicBeans, schemeinfoBeans, commentBeanLists);
	}

	public void addDate(List<TopicBean> topicBeans, List<SchemeinfoBean> schemeinfoBeans,
			List<List<CommentBean>> commentBeanLists) {
		this.topicBeans.addAll(topicBeans);
		this.schemeinfoBeans.addAll(schemeinfoBeans);
		this.commentBeanLists.addAll(commentBeanLists);

	}

	public void setDate(List<TopicBean> topicBean, List<SchemeinfoBean> schemeinfoBean,
			List<List<CommentBean>> commentBeanList) {
		if (null == topicBeans)
			topicBeans = new ArrayList<TopicBean>();
		if (null == schemeinfoBeans)
			schemeinfoBeans = new ArrayList<SchemeinfoBean>();
		if (null == commentBeanLists) {
			commentBeanLists = new ArrayList<List<CommentBean>>();
		}
		topicBeans.clear();
		schemeinfoBeans.clear();
		commentBeanLists.clear();
		for (TopicBean str : topicBean) {
			topicBeans.add(str);
		}

		for (SchemeinfoBean schemeinfo : schemeinfoBean) {
			schemeinfoBeans.add(schemeinfo);
		}
		for (List<CommentBean> li : commentBeanList) {
			List<CommentBean> l = new ArrayList<CommentBean>();
			for (CommentBean str : l) {
				l.add(str);
			}
			commentBeanLists.add(l);
		}
	}

	public List<TopicBean> getTopicBeans() {
		return topicBeans;
	}

	@Override
	public int getCount() {
		if (topicBeans == null) {
			return 0;
		}
		return topicBeans.size();
	}

	@Override
	public Object getItem(int position) {

		return position;
	}

	@Override
	public long getItemId(int position) {

		return position;
	}

	@Override
	public View getView(final int position, View view, ViewGroup parent) {
		ViewHolder holder;
		// 判断View是否为空
		if (view == null) {
			holder = new ViewHolder();
			// LayoutInflater inflater = LayoutInflater.from(context);
			// 得到布局文件
			view = LayoutInflater.from(context).inflate(R.layout.circle_person_info_item, null);
			holder.tv_Price = (TextView) view.findViewById(R.id.tv_Price);
			holder.tv_Projected_bonus = (TextView) view.findViewById(R.id.tv_Projected_bonus);
			holder.tv_Total_amount = (TextView) view.findViewById(R.id.tv_Total_amount);
			holder.tv_item_documentary = (TextView) view.findViewById(R.id.tv_item_documentary);
			holder.lr_hodel = (LinearLayout) view.findViewById(R.id.lr_hodel);
			 holder.ivTypeId=(ImageView) view.findViewById(R.id.iv_type_id);
			 holder.tv_circle_time=(TextView) view.findViewById(R.id.tv_time);
			 holder.tv_detail=(TextView) view.findViewById(R.id.tv_item_detail);
			 holder.tv_sns_num=(TextView) view.findViewById(R.id.tv_sns_num);
			 holder.tv_info_num=(TextView) view.findViewById(R.id.tv_info_num);
			 holder.ivHongbaoShow=(ImageView) view.findViewById(R.id.iv_hongbao_show);

			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}

		if (topicBeans.get(position).hb.equals("1")) {
			holder.ivHongbaoShow.setVisibility(View.VISIBLE);
		}else{
			holder.ivHongbaoShow.setVisibility(View.GONE);
		}
		if (topicBeans.get(position).detail.equals("")) {
			holder.tv_detail.setVisibility(View.GONE);
			holder.tv_detail.setText(topicBeans.get(position).detail);
		} else {
			holder.tv_detail.setVisibility(View.VISIBLE);
			holder.tv_detail.setText(topicBeans.get(position).detail);
		}

		if (topicBeans.get(position).getPlayTypeID().startsWith("72")) {
			holder.ivTypeId.setBackgroundResource(R.drawable.bet_loty_logo_jczq_main);

		} else if (topicBeans.get(position).getPlayTypeID().startsWith("45")) {
			holder.ivTypeId.setBackgroundResource(R.drawable.logo_sfc);


		}else{

			holder.ivTypeId.setBackgroundResource(R.drawable.bet_loty_logo_jclq_main);
		}
		final String playTypeId=topicBeans.get(position).getPlayTypeID();
			if (topicBeans.get(position).getIsopen().equals("False")) {

				if (TimeCompare(topicBeans.get(position).getStoptime())) {

					if (!topicBeans.get(position).cancopy) {
						holder.tv_item_documentary.setText("不可跟单");
						holder.tv_item_documentary.setEnabled(false);
					} else {
						holder.tv_item_documentary.setText("跟单");
						holder.tv_item_documentary.setEnabled(true);
						if (topicBeans.get(position).getPlayTypeID().startsWith("45")) {
							holder.ivTypeId.setBackgroundResource(R.drawable.logo_sfc);
							holder.tv_item_documentary.setText("北单");
							holder.tv_item_documentary.setEnabled(false);
						}



					}

					holder.tv_item_documentary.setBackgroundResource(R.drawable.circle_person_info_copy_pay_bg);

					Log.e("time", "1");
				} else {
					Log.e("time", "1");
					holder.tv_item_documentary.setText("待开奖");
					holder.tv_item_documentary.setBackgroundResource(R.drawable.circle_person_info_copy_pay_bg);
					holder.tv_item_documentary.setEnabled(false);
				}

			} else {
				String iswin = topicBeans.get(position).getIswin();
				if (iswin.equals("0")) {
					holder.tv_item_documentary.setText("未中奖");
					holder.tv_item_documentary.setBackgroundResource(R.drawable.circle_person_info_pay_bg);
					holder.tv_item_documentary.setEnabled(false);
				} else {
					holder.tv_item_documentary.setText("已中奖");
					holder.tv_item_documentary.setBackgroundResource(R.drawable.circle_person_info_copy_pay_bg);
					holder.tv_item_documentary.setEnabled(false);
				}

			}
			List<CommentBean> commentBeans = commentBeanLists.get(position);
			if (commentBeans.isEmpty()) {
				holder.tv_info_num.setText("0");
			}else {
				holder.tv_info_num.setText(commentBeans.size()+"");
			}
			String up = topicBeans.get(position).up;
			if (up.equals("")) {
				holder.tv_sns_num.setText("0");
			}else {
				holder.tv_sns_num.setText((up.split(",")).length+"");
			}


		String passTypeInfo = schemeinfoBeans.get(position).passTypeInfo;
		String preBetType = schemeinfoBeans.get(position).preBetType;
		String pasString = passTypeInfo.split(",")[passTypeInfo.split(",").length - 1];
		int multiple = Integer.parseInt(pasString.substring(0, pasString.length() - 1));
		int buymoney = Integer.parseInt(schemeinfoBeans.get(position).buymoney);
		final int Price = buymoney / multiple;

		holder.tv_Price.setText(Price + "");
//		if (topicBeans.get(position).yjjj != null && !topicBeans.get(position).yjjj.equals("null")) {
//			;
//			if (topicBeans.get(position).yjjj.equals("0.00")||topicBeans.get(position).yjjj.equals("0")||topicBeans.get(position).yjjj.equals("0.0")) {
//				holder.tv_Projected_bonus.setText("0.0");
//			}else {
//			holder.tv_Projected_bonus.setText(df.format(Double.parseDouble(topicBeans.get(position).yjjj)));
//			}
//		} else {
//			holder.tv_Projected_bonus.setText((int) Double.parseDouble("0.0") + "");
//		}


		int followNum=Integer.parseInt(topicBeans.get(position).follCount);
		if (followNum<10){
			holder.tv_Projected_bonus.setText( "一星");
		}else if(followNum<20){
			holder.tv_Projected_bonus.setText( "二星");
		}else if(followNum<30){
			holder.tv_Projected_bonus.setText( "三星");
		}else if(followNum<40){
			holder.tv_Projected_bonus.setText( "四星");
		}else {
			holder.tv_Projected_bonus.setText( "五星");

		}

		String datatime = topicBeans.get(position).datetime;
		String daString = "订单时间："+datatime.substring(5, 7) + "月" + datatime.substring(8, 10) + "日 " + datatime.substring(11, 13)
				+ ":" + datatime.substring(14, 16);
		Log.e("ssss", datatime);
		holder.tv_circle_time.setText(daString);
		holder.tv_Total_amount.setText((int) Double.parseDouble(schemeinfoBeans.get(position).buymoney) + "");// 总钱数

		final int cid = topicBeans.get(position).id;
		String name = topicBeans.get(position).name;
		final String isname;
		if (isMobileNO(name)) {
			isname = name.substring(0, 3) + "****" + name.substring(7, name.length());

		} else {
			isname = name;

		}


		holder.tv_item_documentary.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// MyToast.getToast(context, topicBeans.get(position).id+"跟单").show();
				Intent intent = new Intent(context, DocumentaryActivity.class);
				intent.putExtra("cid", cid);
				intent.putExtra("name", isname);
				intent.putExtra("Price", Price);
				intent.putExtra("playtypeid", playTypeId);
				context.startActivity(intent);
			}
		});

		holder.lr_hodel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String name = topicBeans.get(position).name;

				// TODO Auto-generated method stub
				id = topicBeans.get(position).getUserid() + "";
				sumid = topicBeans.get(position).getSchemeid() + "";

//				pd = BaseHelper.showProgress(context, "", "加载中...", true, false);


				ProgressDialogBar.startProgress(context, "xxs", true);

				if (topicBeans.get(position).getIsopen().equals("False")) {
					isopen = "0";
					// pd = BaseHelper.showProgress(context, "", "加载中...", true, false);

					// Toast.makeText(context, "该方案内容开奖后可见！", Toast.LENGTH_SHORT).show();
					GetMyAsynTask getMyAsynTask = new GetMyAsynTask();
					getMyAsynTask.execute();

				} else {
					isopen = "1";

					GetMyAsynTask getMyAsynTask = new GetMyAsynTask();
					getMyAsynTask.execute();
				}

			}
		});
		return view;
	}

	public boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("1[0-9]{10}");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/** 静态类 */
	static class ViewHolder {
		LinearLayout lr_hodel;
		TextView tv_Total_amount;
		TextView tv_Price;// 赔率
		TextView tv_Projected_bonus;// 排序
        ImageView ivTypeId,ivHongbaoShow;
		TextView tv_item_documentary,tv_circle_time,tv_detail,tv_info_num,tv_sns_num;
	}

	private boolean TimeCompare(String date1) {
		// 格式化时间
		boolean isStop = false;
		SimpleDateFormat CurrentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// String date1="2015-01-25 09:12:09";
		// String date2="2015-01-29 09:12:11";

		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间

		Log.e("time", CurrentTime.format(curDate) + "," + date1);
		try {

			Date beginTime = curDate;
			Date endTime = CurrentTime.parse(date1);
			if ((endTime.getTime() - beginTime.getTime()) > 0) {
				isStop = true;
			} else {
				isStop = false;
			}
			// 判断是否大于两天

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return isStop;

	}

	/*** 异步任务 用来后台获取数据 */
	class GetMyAsynTask extends AsyncTask<Void, Integer, String> {
		/**
		 * 在后台执行的程序
		 */
		@Override
		protected String doInBackground(Void... params) {
			getinfo = "{\"id\":" + sumid + "}";

			getopt = "15";
			Log.i("x", "投注接口 opt :" + getopt);
			Log.i("x", "投注方案详情  info  " + getinfo);

			// 加入验证后有问题,没有传key值
			getkey = App.key;
			getimei = RspBodyBaseBean.getTime();
			getimei = RspBodyBaseBean.getIMEI(context);
			;
			// Log.i("x", "投注方案详情 key " + key);
			// id = adapter.getTopicBeans().get(getInfoPosition).getUserid() + "";
			getcrc = RspBodyBaseBean.getCrc(gettime, getimei, getkey, getinfo, id);
			// Log.i("x", "投注方案详情 crc " + crc);
			getauth = RspBodyBaseBean.getAuth(getcrc, gettime, getimei, id + "");
			// Log.i("x", "投注方案详情=== auth " + auth);
			String[] values = { getopt, getauth, getinfo };
			String result = HttpUtils.doPost(App.names, values, App.path);
			Log.e(TAG, "晒单" + RequestParams.convertParamsfor(context, getopt, getinfo, id));
			Log.e("x", "得到投注内容   " + result);
			scheme = new Schemes();
			if ("-500".equals(result))
				return result;

			if (null == result)
				return "1";
			//
			try {

				JSONObject item = new JSONObject(result);

				if ("0".equals(item.optString("error"))) {
					String schemeList = item.optString("schemeList");

					JSONArray array = new JSONArray(schemeList);

					JSONArray jsonArray2 = new JSONArray(array.toString());

					if (jsonArray2.length() == 0)
						return "1";
					// 如果取消了 则停止
					if (this.isCancelled()) {
						Log.i("x", "取消了异步。。。。");
						return null;
					}
					JSONObject items2 = array.getJSONObject(0);
					scheme.setId(items2.optString("id"));
					// 设置订单编号
					String schemeNum = items2.optString("SchemeNumber");
					// scheme.setSchemeNumber(schemeNum.equals("")
					// ? LotteryUtils.getSchemeNum(App.lottery.getLotteryID(),
					// App.lottery.getIsuseName(),
					// circleBean.topic.get(getInfoPosition).getSchemeid())
					// : schemeNum);
					scheme.setSchemeNumber(schemeNum);
					scheme.setIsHide(items2.optInt("isHide"));
					scheme.setSecretMsg(items2.optString("secretMsg"));
					scheme.setAssureMoney(items2.optDouble("assureMoney"));
					scheme.setAssureShare(items2.optInt("assureShare"));
					scheme.setBuyed(items2.optString("buyed"));
					scheme.setInitiateName(items2.optString("initiateName"));
					scheme.setInitiateUserID(items2.optString("initiateUserID"));
					String isPurchasing = items2.optString("isPurchasing");
					if ("".equals(isPurchasing)) {
						isPurchasing = isJoin + "";
					}
					scheme.setIsPurchasing(isPurchasing);

					// // 设置订单期号
					// scheme.setIsuseID(App.lottery.getIsuseId());
					// scheme.setIsuseName(App.lottery.getIsuseName());

					scheme.setLevel(items2.optInt("level"));
					scheme.setLotteryID(items2.optString("lotteryID"));
					scheme.setLotteryName(items2.optString("lotteryName"));
					scheme.setLotteryNumber(items2.optString("lotteryNumber"));
					scheme.setMoney(items2.optInt("money"));
					scheme.setPlayTypeID(items2.optInt("playTypeID"));
					scheme.setPlayTypeName(items2.optString("playTypeName"));
					scheme.setQuashStatus(items2.optInt("quashStatus"));
					scheme.setRecordCount(items2.optInt("recordCount"));
					scheme.setSchedule(items2.optInt("schedule"));
					scheme.setSchemeBonusScale(items2.optDouble("schemeBonusScale"));
					scheme.setSchemeIsOpened(items2.optString("schemeIsOpened"));
					scheme.setSecrecyLevel(items2.optInt("secrecyLevel"));
					scheme.setSerialNumber(items2.optInt("serialNumber"));
					scheme.setShare(items2.optInt("share"));
					scheme.setShareMoney(items2.optInt("shareMoney"));
					scheme.setSurplusShare(items2.optInt("surplusShare"));
					scheme.setTitle(items2.optString("title"));
					scheme.setWinMoneyNoWithTax(items2.optDouble("winMoneyNoWithTax"));
					scheme.setWinNumber(items2.optString("winNumber"));
					// 设置订单下单时间
					scheme.setDateTime(LotteryUtils.getSchemeTime(System.currentTimeMillis()));

					scheme.setDescription(items2.optString("description"));
					scheme.setIsChase(items2.optInt("isChase"));
					scheme.setChaseTaskID(items2.optInt("chaseTaskID"));
					// 设置倍数
					scheme.setMultiple(items2.optInt("Multiple"));
					// scheme.setMultiple(20);

					scheme.setFromClient(items2.optInt("fromClient"));
					scheme.setMyBuyMoney(item.optInt("myBuyMoney") + "");
					scheme.setMyBuyShare(item.optInt("myBuyShare"));

					String schemeStatus = "待出票";
					try {
						schemeStatus = items2.getString("schemeStatus");
					} catch (JSONException e) {
						// do nothing
					}
					scheme.setSchemeStatus(schemeStatus);

					JSONArray array_contents = new JSONArray(items2.optString("buyContent"));
					List<LotteryContent> contents = new ArrayList<LotteryContent>();
					LotteryContent lotteryContent;
					for (int k = 0; k < array_contents.length(); k++) {
						lotteryContent = new LotteryContent();
						try {
							JSONArray array2 = new JSONArray(array_contents.optString(k));

							lotteryContent.setLotteryNumber(array2.getJSONObject(0).optString("lotteryNumber"));
							lotteryContent.setPlayType(array2.getJSONObject(0).optString("playType"));
							lotteryContent.setSumMoney(array2.getJSONObject(0).optString("sumMoney"));
							lotteryContent.setSumNum(array2.getJSONObject(0).optString("sumNum"));
							contents.add(lotteryContent);
						} catch (Exception e) {
							JSONObject array2 = new JSONObject(array_contents.optString(k));

							lotteryContent.setLotteryNumber(array2.optString("lotteryNumber"));
							lotteryContent.setPlayType(array2.optString("playType"));
							lotteryContent.setSumMoney(array2.optString("sumMoney"));
							lotteryContent.setSumNum(array2.optString("sumNum"));
							contents.add(lotteryContent);
						}
					}
					scheme.setBuyContent(contents);

					if (this.isCancelled()) {
						// pd.dismiss();
						Log.i("x", "取消了异步。。。。");
						return null;
					}
					return "0";
				}
			} catch (Exception e) {
				Log.i("x", "myAllLottery 错误" + e.getMessage());
			}

			return "-1";
		}

		@Override
		protected void onPostExecute(String result) {
			if (null == result)
				return;
			if ("1".equals(result)) {
				getMyHandler.sendEmptyMessage(-1);
			}
			getMyHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}





	/**
	 * 进行页面刷新
	 */
	@SuppressLint("HandlerLeak")
	class getMyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (pd != null) {
				pd.dismiss();
			}

			ProgressDialogBar.stopProgress();
			switch (msg.what) {
			case 0:
				Intent intent_info;
				if ("72".equals(scheme.getLotteryID()) || "73".equals(scheme.getLotteryID())
						|| "45".equals(scheme.getLotteryID())) {

					intent_info = new Intent(context, MyCommonLotteryInfo_jc_other.class);
					App.scheme=scheme;
					intent_info.putExtra("scheme", scheme);

					intent_info.putExtra("id", id);
					intent_info.putExtra("isopen", isopen);

				} else {
					intent_info = new Intent(context, MyCommonLotteryInfo_other.class);
					App.scheme=scheme;
					intent_info.putExtra("scheme", scheme);
					intent_info.putExtra("id", id);
				}
				context.startActivity(intent_info);
				break;
			default:
				break;
			case -1:
				MyToast.getToast(context, "没有数据").show();
				break;
			case -500:
				MyToast.getToast(context, "连接超时").show();
				break;
			}
			super.handleMessage(msg);
		}
	}

}
